import { defineStore } from 'pinia';
import { IS_SCREENLOCKED } from '@/store/mutation-types';
import { storage } from '@/utils/Storage';
import projectSetting from '@/settings/projectSetting';

// 长时间不操作默认锁屏时间
const initTime = projectSetting.screenLockSetting.lockTime * 60;

const isLocked = storage.get(IS_SCREENLOCKED, false);

export type IScreenLockState = {
  isLocked: boolean; // 是否锁屏
  lockTime: number;
  autoLockEnabled: boolean; // 是否启用自动锁屏功能
};

export const useScreenLockStore = defineStore({
  id: 'app-screen-lock',
  state: (): IScreenLockState => ({
    isLocked: isLocked === true, // 是否锁屏
    lockTime: isLocked == 'true' ? initTime : 0,
    autoLockEnabled: projectSetting.screenLockSetting.autoLockEnabled, // 是否启用自动锁屏功能
  }),
  getters: {},
  actions: {
    setLock(payload: boolean) {
      // 手动锁屏和解锁不受自动锁屏设置影响
      this.isLocked = payload;
      storage.set(IS_SCREENLOCKED, this.isLocked);
    },
    setLockTime(payload = initTime) {
      // 只有在启用自动锁屏时才设置锁屏时间
      if (!this.autoLockEnabled) return;
      this.lockTime = payload;
    },
    setAutoLockEnabled(payload: boolean) {
      this.autoLockEnabled = payload;
      if (!payload) {
        // 如果禁用自动锁屏功能，重置锁屏时间但不解锁
        this.lockTime = 0;
      }
    },
    // 新增：手动触发锁屏（不受自动锁屏设置影响）
    manualLock() {
      this.setLock(true);
    },
  },
});